package com.yummy.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.yummy.common.RoleConstants;
import com.yummy.dto.QueryEmployeeVo;
import com.yummy.entity.Employee;
import com.yummy.service.EmployeeService;
import com.yummy.common.BaseResponse;
import com.yummy.common.MD5Util;
import com.yummy.common.TokenUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yinbo
 */
@RestController
@RequestMapping("/emp")
public class EmployeeController {

	@Autowired
	private EmployeeService employeeService;

	@Autowired
	TokenUtils tokenUtils;

	@Autowired
	private RedisTemplate redisTemplate;


	Logger logger = LoggerFactory.getLogger(EmployeeController.class);

	@PostMapping("/login")
	public BaseResponse login(@RequestBody Employee employee) throws NoSuchAlgorithmException {
		String username = employee.getUsername();
		String password = employee.getPassword();
		logger.info("登录信息==>username:"+username+"\tpassword:"+password);
		logger.info(MD5Util.getMD5(password));
		Employee loginEmp = employeeService.login(username, MD5Util.getMD5(password));
		//登录失败
		if (loginEmp == null){
			return BaseResponse.fail().message("登录失败，用户名或密码错误");
		}else {
			String token = tokenUtils.getToken(loginEmp.getId().toString(), password);
			logger.debug("当前用户token:"+token);
			//缓存token和店铺id
			redisTemplate.opsForValue().set(token,loginEmp.getStoreId().toString(),2, TimeUnit.HOURS);
			return BaseResponse.success().data("username",username).data("Authorization",token).data("userId",loginEmp.getId());
		}
	}

	@PostMapping("/registerAdmin")
	public BaseResponse register(@RequestBody Employee employee) throws NoSuchAlgorithmException {
		logger.info("注册人："+employee.toString());
//		employee.setRoleId(RoleConstants.Code_Admin);
		employee.setPassword(MD5Util.getMD5(employee.getPassword()));
		//未注册店铺时店铺id为-1
		employee.setStoreId(-1);
		employee.setRoleId(1);
		boolean result = employeeService.registerAdmin(employee);
		if (result){
			return BaseResponse.success().message("注册成功，快去登录吧");
		}
		return BaseResponse.fail().message("注册失败，请重试");
	}

	@PostMapping("/queryAll")
	public BaseResponse queryEmployees(@RequestBody QueryEmployeeVo queryEmployeeVo, HttpServletRequest request){

		Employee currentEmp = tokenUtils.getCurrentEmp(request);
		System.out.println(currentEmp);
		Integer currentStore = currentEmp.getStoreId();
		if (currentStore==null){
			return BaseResponse.fail().message("请先注册店铺");
		}
		System.out.println("current==>"+currentStore);
		queryEmployeeVo.setStoreId(currentStore);
		System.out.println(queryEmployeeVo);
		PageInfo<Employee> pageInfo = employeeService.queryByPageAndCondition(queryEmployeeVo);
		return BaseResponse.success().data("pageInfo",pageInfo);
	}

	@PostMapping("/add")
	public BaseResponse addEmployee(@RequestBody Employee employee,HttpServletRequest request) throws NoSuchAlgorithmException {
		Integer currentStore = tokenUtils.getCurrentStore(request);
		employee.setStoreId(currentStore);
		employee.setRoleId(RoleConstants.Code_Employee);
		employee.setPassword(MD5Util.getMD5(employee.getPassword()));
		logger.info(employee.toString());
		boolean result = employeeService.addEmployee(employee);
		if (result){
			return BaseResponse.success().message("新增成功");
		}
		return BaseResponse.fail().message("新增失败");
	}


	@PostMapping("/update")
	public BaseResponse editEmployee(@RequestBody Employee employee,HttpServletRequest request) throws NoSuchAlgorithmException {
		Integer currentStore = tokenUtils.getCurrentStore(request);
		logger.info(employee.toString());
		employee.setStoreId(currentStore);
		employee.setRoleId(RoleConstants.Code_Employee);
		employee.setPassword(MD5Util.getMD5(employee.getPassword()));
		boolean result = employeeService.editEmployee(employee);
		if (result){
			return BaseResponse.success().message("修改成功");
		}
		return BaseResponse.fail().message("修改失败");
	}


	@GetMapping("/remove")
	public BaseResponse removeEmployees(@RequestParam String[] ids){
		System.out.println("ids==>"+ids);
		for (String id : ids) {
			System.out.println(id);
		}
		boolean result = employeeService.removeEmployees(ids);
		if (result){
			return BaseResponse.success().message("删除成功");
		}else {
			return BaseResponse.fail().message("删除失败");
		}
	}
	@GetMapping("/export")
	public void fileExport(HttpServletResponse response) throws Exception {
		// 从数据库查询出所有的数据
		List<Employee> list = employeeService.queryAll();
		// 通过工具类创建writer 写出到磁盘路径
		//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
		// 在内存操作，写出到浏览器
		ExcelWriter writer = ExcelUtil.getWriter(true);
		//自定义标题别名
		writer.clearHeaderAlias();
		writer.addHeaderAlias("id", "编号");
		writer.addHeaderAlias("username", "用户名");
		writer.addHeaderAlias("password", "密码");
		writer.addHeaderAlias("phone", "电话");
		writer.addHeaderAlias("sex", "性别");
		writer.addHeaderAlias("idNumber", "身份证号");

		// 一次性写出list内的对象到excel，使用默认样式，强制输出标题
		writer.write(list, true);

		// 设置浏览器响应的格式
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
		String fileName = URLEncoder.encode("员工信息", "UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

		ServletOutputStream out = response.getOutputStream();
		writer.flush(out, true);
		out.close();
		writer.close();
	}


	/**
	 * excel 导入
	 *
	 * @param file
	 * @throws Exception
	 */
	@PostMapping("/import")
	public BaseResponse fileImport(MultipartFile file,HttpServletRequest request) throws Exception {
		InputStream is = file.getInputStream();
		ExcelReader reader = ExcelUtil.getReader(is);

		//：忽略表头的中文，直接读取表的内容
		List<List<Object>> list = reader.read(1);

		Integer currentStore = tokenUtils.getCurrentStore(request);
		System.out.println(request+"======"+currentStore);
		List<Employee> employees = CollUtil.newArrayList();
		for (List<Object> row : list) {
			Employee employee = new Employee();
			employee.setUsername(row.get(1).toString());
			employee.setPassword(row.get(2).toString());
			employee.setRoleId(RoleConstants.Code_Employee);
			employee.setPhone(row.get(3).toString());
			employee.setSex(row.get(4).toString());
			employee.setIdNumber(row.get(5).toString());
			employee.setStoreId(currentStore);
			employees.add(employee);
		}

		boolean result = employeeService.insertBatch(employees);
		if (result){
			return BaseResponse.success();
		}
		return BaseResponse.fail();
	}

	@GetMapping("/setStatus/{id}/{status}")
	public BaseResponse setStatus(@PathVariable("id") String id,@PathVariable("status")String status ){
		System.out.println(id+"----"+status);
		boolean result = employeeService.updateStatus(id,status);
		if (result){
			return BaseResponse.success();
		}
		return BaseResponse.fail().data("status",employeeService.findEmpById(id).getStatus());
	}
}
